package com.dyrnq.seckill.service.impl.v2;

import com.dyrnq.seckill.entity.OrderInfo;
import com.dyrnq.seckill.entity.SeckillGoods;
import com.dyrnq.seckill.entity.SeckillOrder;
import com.dyrnq.seckill.mapper.OrderInfoMapper;
import com.dyrnq.seckill.mapper.SeckillGoodsMapper;
import com.dyrnq.seckill.mapper.SeckillOrderMapper;
import com.dyrnq.seckill.mq.Producer;
import com.dyrnq.seckill.service.ISeckillSvc;
import com.dyrnq.seckill.service.impl.AbstractSeckillSvcImpl;
import com.dyrnq.seckill.service.impl.SeckillOrderService;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Component("seckillSvc_v2")
public class SeckillSvcImpl extends AbstractSeckillSvcImpl implements ISeckillSvc {
    protected SeckillSvcImpl(SeckillOrderService seckillOrderService, SeckillGoodsMapper seckillGoodsMapper, SeckillOrderMapper seckillOrderMapper, OrderInfoMapper orderInfoMapper, RedissonClient redissonClient, StringRedisTemplate stringRedisTemplate, Producer producer) {
        super(seckillOrderService, seckillGoodsMapper, seckillOrderMapper, orderInfoMapper, redissonClient, stringRedisTemplate, producer);
    }

    @Override
    @Transactional
    public long doSeckill(long goods_id, long user_id) {
        SeckillGoods seckillGoods = seckillGoodsMapper.selectById(goods_id);
        Integer stockCount = seckillGoods.getStockCount();

        if (stockCount <= 0) {
            throw new RuntimeException("库存为0");
        }
        int effect = seckillGoodsMapper.updateStockCount(seckillGoods.getId(), 1, stockCount);
        if (effect == 0) {
            throw new RuntimeException("异常");
        }

        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setCreateDate(LocalDateTime.now());
        orderInfo.setGoodsId(goods_id);
        orderInfo.setUserId(user_id);
        orderInfo.setStatus(0);
        orderInfoMapper.insert(orderInfo);

        SeckillOrder seckillOrder = new SeckillOrder();
        seckillOrder.setOrderId(orderInfo.getId());
        seckillOrder.setUserId(user_id);
        seckillOrder.setGoodsId(goods_id);
        seckillOrderMapper.insert(seckillOrder);
        return 0;
    }

    @Override
    @Transactional
    public long doSeckill_1user1order(long goods_id, long user_id) {
        return super.doSeckill_1user1order(goods_id, user_id);
    }

    @Override
    public long doSeckill_1user1order_redis(long goods_id, long user_id) {
        return super.doSeckill_1user1order_redis(goods_id, user_id);
    }
}
